import React, {Component, PropTypes} from "react";
import {Form, Input, Modal, Radio, Button, Tree, message, Icon, Spin, Select} from "antd";
import objectAssign from 'object-assign'
import {WeaDialog, WeaNewScroll, WeaInput, WeaSelect, WeaTree} from "ecCom";
import * as apis from "./apis";
import * as util from "./util";
import "./index.less";
import {WeaLocaleProvider} from 'ecCom'
const getLabel = WeaLocaleProvider.getLabel
const FormItem = Form.Item;


const formItemLayout = {
    labelCol: {span: 7},
    wrapperCol: {span: 17},
};

const intialState = {
   // selectedKey: "0", /**选中的节点*/
    expandedKeys: [], /**展开的节点*/
    operatingKey: "", /**鼠标移入的节点*/
    clickExpanded: true, /**点击展开节点*/
    treeData: [],
    
};

class WeaFavouriteBrowser extends Component {
    constructor(props) {
        super(props);
        let {favname, favouritetype, link, objid, importantlevel, visible} = props;
        if (!link) {
            link = location.pathname + location.hash;
        }
        this.state = {
            visible: false,
            formData: {favname, favouritetype, link, objid, importantlevel},
            typeList: [],
            levelList: [],
            treeData: [], /**树节点的数据*/
            selectedKey: "0", /**选中的节点*/
            expandedKeys: [], /**展开的节点*/
            operatingKey: "", /**鼠标移入的节点*/
            clickExpanded: true, /**点击展开节点*/
            spinning: true,
            tip: `${getLabel(82275, '数据加载中，请稍候...')}`,
            initTreeData:[],
            loadedTreeData:[]
        };
    }

    componentWillUpdate(nextProps, nextState, nextContext) {
        this.props.onOpen && this.props.onOpen(this.props.visible,nextProps.visible);
    }

    componentWillReceiveProps(nextProps) {
        let {visible} = nextProps;
        this.setState({visible});

        if (this.props.visible != visible && visible) {
            /**
             * 参数解析
             */
            let {
                favname, favouritetype, link, objid, importantlevel, visible
            } = nextProps;
            if (!link) {
                link = location.pathname + location.hash;
            }
            let formData = {
                favname, favouritetype, link, objid, importantlevel
            };
            this.setState({spinning: true, tip: `${getLabel(82275, '数据加载中，请稍候...')}`, ...intialState, formData});
            this.initForm();
            this.loadTreedata("0");
        }
    }

	componentDidUpdate() {
        jQuery(".fav-browser-container .wea-new-scroll").css({"height":"100%"})
    }

    componentDidMount() {
        jQuery(".fav-browser-container .wea-new-scroll").css({"height":"100%"})
    }

	
    componentWillUnmount() {
        if (!!this.intervalid) {
            window.clearInterval(this.intervalid);
        }
    }
    initForm = () => {
        apis.init().then(resdata => {
            let {typeList, favTypeMap} = resdata;
            let tempList = [];
            typeList.forEach(item => {
                let {id} = item;
                if (id != "0") {
                    tempList.push(item);
                }
            });

            let levelList = [];
            for (let key in favTypeMap) {
                let levelItem = {};
                levelItem.id = key;
                levelItem.name = favTypeMap[key];
                levelList.push(levelItem);
            }

            this.setState({typeList: [...tempList], levelList});
        });
    }

    getRadios = (dataList) => {
        let list = [...dataList];
        return list.map(item => {
            return {key: item.id, showname: item.name, selected: item.selected};
        });
    }

    getSelect = (typeList, value, disabled) => {
        let options = typeList.map(item => {
            let obj = {};
            obj.key = item.id;
            obj.showname = item.name;
            return obj;
        });

        let viewAttr = 2;
        if (disabled) {   //只读
            viewAttr = 1;
        }

        return (
            <WeaSelect options={options} value={value} viewAttr={viewAttr} onChange={this.saveFavouritetype}>
            </WeaSelect>
        );
    }

    saveFavName = (value) => {
        const {formData} = this.state;
        formData.favname = value;
    }

    saveImportantlevel = (value) => {
        
        const {formData} = this.state;
        formData.importantlevel = value;
    }

    saveFavouritetype = (value) => {
        const {formData} = this.state;
        formData.favouritetype = value;
    }


    /**
     * 获取表单的元素
     * @returns {Array}
     */
    getFormItems = () => {
        let {typeList, levelList, formData} = this.state;
        let {favname, favouritetype, link, objid, importantlevel=1} = formData;
        importantlevel = String(importantlevel)
        favouritetype = favouritetype + "";
        let items = [];
        items.push(
            <FormItem {...formItemLayout} label={getLabel('22426','收藏标题')}>
                <WeaInput placeholder={getLabel('385874','请输入收藏标题')} defaultValue={favname} viewAttr={3} stringLength={3000} onChange={this.saveFavName} onBlur={this.saveFavName}/>
            </FormItem>
        );
        if (levelList.length > 0) {
            let radios = this.getRadios(levelList);
            items.push(
                <FormItem {...formItemLayout} label={getLabel('18178','重要程度')}>
                    <WeaSelect value={importantlevel} onChange={this.saveImportantlevel} detailtype={3} options={radios}>
                    </WeaSelect>
                </FormItem>
            );
        }


        if (typeList.length > 0) {
            objid = Number(objid);
            let disable = false;
            if (objid > 0) {      //收藏的对象存在，或者消息类型，不可编辑
                disable = true;
            }
            let selectComp = this.getSelect(typeList, favouritetype, disable);

            items.push(
                <FormItem {...formItemLayout} label={getLabel('22242','收藏类型')}>
                    {selectComp}
                </FormItem>
            );
        }

        return items;
    }

    getFormComp = () => {
        let formItems = this.getFormItems();
        return (
            <div className="fav-browser-top">
                <div className="fav-form-title">{getLabel('81711','基本信息')}</div>
                <div className="fav-form-basic">
                    <Form horizontal={true}>{formItems}</Form>
                </div>
            </div>
        );
    }


    

    getTreeComp = () => { 
        return (
            <WeaTree 
                ref='tree'
                addToLast
                hasRadio
                onDatasChange={(data)=>{this.setState({initTreeData:data})}}
                radioCheckedKey={this.state.selectedKey}
                onRadioCheck={(id,radioCheckedKey) => {this.setState({selectedKey:radioCheckedKey})}}
                datas={this.state.initTreeData}
                loadData={(item) => {return this.asyncLoad(item.nodeid)}}
                onAdd={(value, node)=>{return this.addDirectory(node==undefined?'0':node.nodeid,value)}}
                onEdit={(value,node)=>{return this.editDirectory(value,node)}}
            ></WeaTree>
            
        );
    }
    addDirectory=(parentid,favname)=>{
        return new Promise((resolve)=>{            
            apis.saveAddNode({parentid,favname}).then(resdata => {
                let success = resdata.success;               
                if (success==1){
                    let newdata = []
                    newdata.push({
                        'nodeid':resdata.id,
                        "canClick": true, // 标识节点是否可以点击 （单选 多选模式下生效）
                        "icon": '', // 图标展示
                        "isParent": false,  // 父节点标识 
                        "name": favname, // 名称
                        "dragDisabled": true, // 禁止节点拖拽
                        "ops": [
                            {type: 'edit'},
                            {type: 'add'},
                        ],
                    
                    })
                    resolve(newdata[0])
                    
                }
            });
        })

    }
    editDirectory=(value,node)=>{
        let arr = []
        let parentid =  ''
        let favid = node.nodeid
        let favname = value
        if(!node.parentTreeKey){
            parentid='0'
        }else{
            arr=node.treeKey.split('__')
            if(arr.length==3){
                parentid = arr[0]
            }else{
                parentid = arr.slice(arr.length-3,arr.length-2).join().split('-')[1]
            }
            
        }
        return new Promise((resolve)=>{            
            apis.saveEditNode({parentid,favid,favname}).then(resdata => {
                let success = resdata.success;            
                if (success==1){
                    let newdata = []
                    newdata.push({
                        'nodeid':resdata.id,
                        "canClick": true, // 标识节点是否可以点击 （单选 多选模式下生效）
                        "icon": '', // 图标展示
                        "isParent": false,  // 父节点标识
                        "name": favname, // 名称
                        "dragDisabled": true, // 禁止节点拖拽
                        "ops": favid==-1?[]:[
                            {type: 'edit'},
                            {type: 'add'},
                        ],
                    
                    })
                    resolve(newdata[0])
                    
                }
            });
        })
    }
    

    submitData = (evt) => {
        evt.preventDefault();

        var itemValues = this.state.formData;      //获取表单中的所有数据
        if (itemValues) {
            let {favname} = itemValues;
            if (!favname) {
                Modal.error({content: `${getLabel(385876, '收藏标题不能为空！')}`});
                return;
            }
            let dirid = this.state.selectedKey;
            if (dirid == "" || dirid == "0") {
                Modal.error({content: `${getLabel('385877','请选择一个目录！')}`});
                return;
            } else {
                this.setState({spinning: true, tip:`${getLabel(82275, '数据加载中，请稍候...')}`});
                let {link, objid} = this.state.formData;
                let params = objectAssign(itemValues, {link, objid, dirid});
                apis.saveFavourite(params).then(resdata => {
                    this.setState({spinning: false});
                    let {success, msg} = resdata;
                    if (success == "1") {   //保存成功，关闭
                        this.setState({visible: false});
                        this.props.onClose(evt);
                        if (this.props.submitBack) {
                            this.props.submitBack(resdata);
                        }
                    } else {
                        if (!!msg) {
                            Modal.error({content: msg});
                        }
                    }
                });
            }
        } else {    //有错误，提示
            for (let key in err) {
                let {errors} = err[key];
                if (errors.length > 0) {
                    Modal.error({content: errors[0].message});
                    break;
                }
            }
        }

    }
    loadTreedata = (parentId) => {
        return new Promise((resovle,reject)=>{
            apis.loadTree(parentId).then(resdata => {      
                this.setState({spinning: false});      
                let success = resdata.success;
                if (success == "1") {
                    let data = resdata.data;
                    let newdata = [];
                    /**
                     * 设置树节点的数据
                     */
                    data.map((val,index)=>{
                        newdata.push({
                            'nodeid':val.favid,
                            "canClick": true, // 标识节点是否可以点击 （单选 多选模式下生效）
                            "icon": val.child==1?"icon-coms-LargeArea":'', // 图标展示
                            "isParent": val.child==1?true:false,  // 父节点标识
                            "name": val.favname, // 名称
                            "dragDisabled": true, // 禁止节点拖拽
                            "ops": val.favid==-1?[]:[
                                {type: 'edit'},
                                {type: 'add'}],
                        
                        })
                    })
                  
                    if(parentId==0){
                        this.setState({initTreeData:newdata})

                    }else{
                        this.setState({loadedTreeData:newdata})
                    }
                    resovle(this.state.initTreeData)
                } 
            });

        })

    }
    asyncLoad = (nodeid) =>{//这里可以优化
        let that = this
        function fn() {           
            return new Promise((resolve, reject) => {
               resolve(that.loadTreedata(nodeid))  //这是一个异步函数                                                           
            })
        } 
        let fn_1 = async function() {
            await fn();//等待异步操作执行完了后执行的方法
            return new Promise((resolve)=>{ //loadData接口需要一个promise对象，所以这里要包装返回一个promise对象
                const data = {
                    datas: that.state.loadedTreeData
                }
                resolve(data)
            })
        }
        return fn_1();
    }
    selectRoot =()=>{

        this.refs.tree.addRootNode()
    }
    render() {
        let {visible, spinning, tip, treeData} = this.state;
        let title = `${getLabel(22255,'添加收藏')}`;
        let style = {width: 650, height: 600};
        let onCancel = this.props.onClose;
        let buttons = [
            (<Button onClick={this.submitData}>{getLabel('826','确定')}</Button>),
            (<Button onClick={onCancel}>{getLabel('31129','取消')}</Button>)
        ];
        let loadCss = true;
        let params = {visible, title, style, onCancel, buttons, loadCss};

        let formComp = this.getFormComp();

       // let treeComp = this.getTreeComp();
        
        let browHeight = 363;

        return (
            <WeaDialog {...params}>
                <div className="fav-browser-container">
                    <Spin spinning={spinning} tip={tip} size="large" style={{"height": "100%"}}>
                        {formComp}
                        <div className="fav-browser-directory">
                            <div className="fav-directory-title">
                                <div className="fav-directory-text">{getLabel(22246, '目标位置')}</div>
                                <div className="fav-directory-btn" onClick={this.selectRoot}>
                                    <Button title={getLabel(125058,'添加目录')}><Icon type="plus"/></Button>
                                </div>
                            </div>
                            <div className="fav-browser-tree">
                                <WeaNewScroll height={browHeight}>
                                    {this.getTreeComp()}
                                    
                                </WeaNewScroll>
                            </div>
                        </div>
                    </Spin>
                </div>
            </WeaDialog>
        );
    }
}

WeaFavouriteBrowser.PropTypes = {
    onClose: React.PropTypes.func.isRequired
}

export default WeaFavouriteBrowser;